package cn.wolfcode.shop.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**操作cookie的工具类
 * 用来添加cookie并响应给用户的工具类
 */
public class CookieUtil {
    public static void addCookie(HttpServletResponse response,String cookieName,String cookieValue,int expireSeconds){
        Cookie cookie = new Cookie(cookieName,cookieValue);
        //表示/根路径下这个cookie都有效
        cookie.setPath("/");
        cookie.setMaxAge(expireSeconds);
        //响应给客户端
        response.addCookie(cookie);
    }

    /**
     * 从请求中获取指定的cookieName的value
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request,String cookieName){
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0){
            return null;
        }
        for (Cookie cookie : cookies) {
            if(cookieName.equals(cookie.getName())){
                return cookie.getValue();
            }
        }
        return null;
    }
}
